<template>
    <div class="personnel-info-list">
      <a-card :bordered="false" style="width: 100%">
        <div slot="title">
            <a-icon type="left" class="mr10" @click="goBack" />
            <span>个人信息管理</span>
        </div>
        <a-form-model
          :model="personelForm"
          ref="personelFormRef"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="rules"
          style="width: 1000px"
          class="personel-form-wrap"
        >
          <a-form-model-item label="姓名" prop="userName">
            <a-input
              v-model.trim="personelForm.userName"
              :maxLength="10"
              placeholder="请输入姓名"
              style="width: 500px"
            />
          </a-form-model-item>
          <a-form-model-item label="昵称" prop="globalNickName">
            <a-input
              v-model.trim="personelForm.globalNickName"
              :maxLength="20"
              placeholder="请输入昵称"
              style="width: 500px"
            />
          </a-form-model-item>
          <a-form-model-item label="性别" prop="gender">
            <a-radio-group v-model="personelForm.gender" :options="genderList" />
          </a-form-model-item>
          <a-form-model-item label="用户名" class="has-right-edit-btn">
            <span class="text-box">{{ personelForm.account }}</span>
            <!-- 配合后端先隐藏 -->
            <a-button v-if="false" type="primary" @click="commonModify('account')">修改用户名</a-button>
          </a-form-model-item>
          <a-form-model-item label="手机号" class="has-right-edit-btn">
            <span class="text-box">{{ personelForm.phone }}</span>
            <!-- 配合后端先隐藏 -->
            <a-button v-if="false" type="primary" @click="commonModify('phone')">修改手机号</a-button>
          </a-form-model-item>
          <a-form-model-item label="邮箱" class="has-right-edit-btn">
            <span class="text-box">{{ personelForm.email }}</span>
            <!-- 配合后端先隐藏 -->
            <a-button v-if="false" type="primary" @click="commonModify('email')">修改邮箱</a-button>
          </a-form-model-item>
          <a-form-model-item label="密码" class="has-right-edit-btn">
            <span class="text-box">
              ******
            </span>
            <a-button type="primary" @click="commonModify('password')">修改密码</a-button>
          </a-form-model-item>
        </a-form-model>
        <a-button class="bottom-save-btn" type="primary" @click="onSave">保存修改</a-button>
        <!-- 弹窗 -->
        <update-modal
            :isVisible="updateVisible"
            :updateVisibleFn="updateVisibleFn"
            :type="type"
            :submit="modalSubmit"
            :cancel="modalCancel"
            :updatePhoneCode="updatePhoneCode"
            :syncSafePhone="syncSafePhone"
            :phone="personelForm.phone + ''"
        />
      </a-card>
    </div>
  </template>
  
<script>
import { mapGetters } from "vuex";
import updateModal from "./components/modal.vue";
import {
  getPersonelInfo,
  updatePersonelPhone,
  updatePersonelAccount,
  updatePersonelEmail,
  updatePersonelOther,
  resetPassword
} from "@/services/user";
import { commonValidate } from "@/utils/util";
import Regex from "@/utils/regex.js";
import { LOGIN_METHOD_MAP } from "@/config/const"
import { storeQiankun } from 'if-qiankun-config'
import { NAME_TIPS, NAME_EMPTY_TIPS } from '@/utils/consts'
import { dispatchAction } from '@/utils/qiankun'

const { ActionsFromMainSystem } = storeQiankun

export default {
    name: "personnelInfo",
    components: {
      updateModal
    },
    data() {
        return {
            isLoading: false,
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
            personelForm: {
                globalNickName: "", // 昵称
                gender: undefined, // 性別
                phone: "", // 手机
                email: "", // 邮箱
                userName: "", // 姓名
                account: "" // 用户名
            },
            genderList: [
                {label: '男', value: 1},
                {label: '女', value: 2},
                {label: '保密', value: -1}
            ],
            rules: {
                userName: [
                    { required: true, validator: this.onCheckName, trigger: "blur" }
                ],
                globalNickName: [
                    { required: true, message: "请输入昵称", trigger: "blur" }
                ]
            },
            updateVisible: false,
            apiPointer: null,
            type: '',
            phoneCode: '',
            safePhone: ''
        };
    },
    watch: {},
    mounted() {
      this.getInitData() // 初始化数据
    },
    computed: {
      ...mapGetters("account", ["enterpriseId", "loginUserInfo"]),
      // 需要重新登录
      needLogin() {
        let need = false
        const { loginMethod } = this.loginUserInfo
        // 修改当前登录方式要退出
        switch(this.type) {
          case 'phone':
            need = loginMethod === LOGIN_METHOD_MAP.phone;
            break;
          case 'account':
            need = loginMethod === LOGIN_METHOD_MAP.account;
            break;
          case 'email':
            need = loginMethod === LOGIN_METHOD_MAP.email;
            break;
          case 'password':
            need = true
            break;
          default:
        }
        return need
      }
    },
    methods: {
        // 初始化数据
        async getInitData() {
          const userResult = await getPersonelInfo()
          const { code, data } = userResult.data
          if (code !== 200) return
          this.personelForm = data;
        },
        // 姓名的校验
        onCheckName(rule, value, callback) {
          if (!value) {
            callback(new Error(NAME_EMPTY_TIPS));
            return
          }
          let nameFlag = Regex.familyName.test(value) || Regex.familyNameEn.test(value) // 验证中英文
          nameFlag = nameFlag && Regex.familyNameDot.test(value) // 验证·的问题 不会有空格问题，因为输入trim
          if (!nameFlag) {
            callback(new Error(NAME_TIPS));
            return;
          }
          callback()
        },
        // 修改变更
        commonModify(type) {
            this.updateVisible = true;
            this.type = type;
            this.setApiByType();
        },
        updateVisibleFn(flag) {
          this.updateVisible = flag
        },
        // 全部保存
        async onSave() {
          const { globalNickName, userName, gender } = this.personelForm
          const params = {
            nickName: globalNickName,
            userName,
            gender
          }
          const formValid = await commonValidate(this.$refs.personelFormRef)
          if (!formValid) return
          const saveResult = await updatePersonelOther(params)
          const { code, message } = saveResult.data
          if (code !== 200) {
            this.$message.error(message)
            return;
          }
          this.$message.success('修改成功!')
          // dispatchAction(ActionsFromMainSystem.UPDATE_MAIN_APP_TOP_NAME, { loginUserName: userName })
          dispatchAction('UPDATE_MAIN_APP_TOP_NAME', { loginUserName: userName })
        },
        // 更新手机验证码信息
        updatePhoneCode(phoneCode) {
          this.phoneCode = phoneCode
        },
        // 基于当前type获取调用接口
        setApiByType() {
            this.apiPointer = null;
            switch(this.type) {
              // 用户名
              case 'account':
                this.apiPointer = updatePersonelAccount;
                break;
              // 手机号
              case 'phone':
                this.apiPointer = updatePersonelPhone;
                break;
              // 邮箱
              case 'email':
                this.apiPointer = updatePersonelEmail;
                break;
              // 密码
              case 'password':
                this.apiPointer = resetPassword;
                break;
              default:
                this.apiPointer = null;
            }
        },
        // 弹窗部分通用字段修改的提交
        async modalSubmit(params) {
          params.authorizationCode = this.phoneCode // 验证码鉴权赋值
          // 修改密码需要同步手机号
          const isPwd = this.type === 'password'
          isPwd && (params.phone = this.safePhone)
          params.loginMethod = this.loginUserInfo.loginMethod
          const apiResult = await this.apiPointer(params)
          const { code, message } = apiResult.data
          this.safePhone = '' // 立即重置
          if (code !== 200) {
            this.$message.error(message)
            return
          }
          this.$message.success('修改成功!')
          this.updateVisible = false
          // 不需要重新登录
          if (!this.needLogin) {
            this.getInitData() // 重新调用接口获取用户信息
            return
          }
          // 需要重新登录
          dispatchAction(ActionsFromMainSystem.LOG_OUT)
        },
        modalCancel() {
          this.updateVisible = false
        },
        goBack() {
            this.$router.go(-1)
        },
        // 同步第一步的安全手机号
        syncSafePhone(phone) {
          this.safePhone = phone
        }
    }
  };
  </script>
  
  <style lang="less" scoped>
  .personnel-info-list {
    .personel-form-wrap {
      padding-top: 20px;
      width: 800px;
    }
    :deep(.has-right-edit-btn) {
        button {
            margin-left: 10px;
        }
    }
    .bottom-save-btn {
      display: block;
      width: 400px;
      line-height: 40px;
      height: 40px;
      margin-top: 40px;
      margin-left: 300px;
    }
    :deep(.ant-form-item-label) {
        padding-right: 20px;
        label {
          font-size: 14px!important;
        }
    }
    .text-box {
      display: inline-block;
      vertical-align: top;
      margin-top: 5px;
      width: 500px;
      height: 30px;
      line-height: 30px;
    }
    .ant-form-item-children {
      width: 100%;
      display: block;
    }
  }
  </style>
  